﻿using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;
using ZTool.Model.DTO;

namespace ZTool.Model
{
    public class JsonPostSender
    {
        private readonly TimeSpan timeout = TimeSpan.FromSeconds(10);

        private static ResponseDTO ofResDTO(int code, string message, object obj)
        {
            return new ResponseDTO { Code = code, Message = message, Data = obj };
        }

        public string input2Json(InputDTO inputDTO)
        {
            return JsonConvert.SerializeObject(inputDTO);
        }

        public async Task<ResponseDTO> SendJsonData(string url, InputDTO inputDTO)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.Timeout = timeout;

                var jsonData = input2Json(inputDTO);
                StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                try
                {
                    HttpResponseMessage response = await httpClient.PostAsync(url, content);

                    if (response.IsSuccessStatusCode)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();

                        return JsonConvert.DeserializeObject<ResponseDTO>(responseContent);
                    }
                    else
                    {
                        return ofResDTO(-1, "POST request failed with status code " + response.StatusCode, null);
                    }
                }
                catch (TaskCanceledException)
                {
                    return ofResDTO(-1, "Request timed out", null);
                }
                catch (Exception ex)
                {
                    return ofResDTO(-1, "An error occurred: " + ex.Message, null);
                }
            }
        }
    }
}
